package com.tang.provider.register;

import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Tang
 * @classname ServerRegister
 * @description [ 服务注册类，把当前服务器地址，注册到zk下面，供消费者调用 ]
 * @date 2021/1/21 21:40
 */
@Slf4j
@Component
public class ServerRegister {

    @Value("${register.address}")
    private String registerAddress;

    private static final String ZK_REGISTER_PATH = "/rpc";

    public void register(String data) {
        if (data != null) {
            ZkClient zkClient = connectServer();
            if (zkClient != null) {
                addRootNode(zkClient);
                createNode(zkClient,data);
            }
        }
    }

    private ZkClient connectServer() {
        ZkClient client = new ZkClient(registerAddress);
        return client;
    }

    private void addRootNode(ZkClient client) {
        boolean exists = client.exists(ZK_REGISTER_PATH);
        if (!exists) {
            client.createPersistent(ZK_REGISTER_PATH);
            log.info("创建zk主节点{}",ZK_REGISTER_PATH);
        }
    }

    private void createNode(ZkClient zkClient, String data) {
        String path = zkClient.create(ZK_REGISTER_PATH + "/provider", data, CreateMode.EPHEMERAL_SEQUENTIAL);
        log.info("创建zk数据节点({}=>{})",path,data);
        zkClient.subscribeChildChanges(ZK_REGISTER_PATH + "/provider", new IZkChildListener() {
            @Override
            public void handleChildChange(String s, List<String> list) throws Exception {

            }
        });
    }

}